import React, { useEffect, useState, useRef, useCallback } from 'react'
import {
  StyleSheet, 
  SafeAreaView, 
  View,
  Text
} from 'react-native'
import { Header } from '../../components'
import { pxToPt } from '../../utils'
import { useNavigation, useRoute } from '@react-navigation/native'
import {useSelector, useDispatch } from 'react-redux'
import { MESSAGE_CONTENT_TYPE, MESSAGE_TYPE } from '../../types/message'
import { Avatar, GiftedChat } from 'react-native-gifted-chat'
import message, {
  RESET_CHAT_UNREAD_NUMBER,
  UPDATE_CURRENT_CHAT_USER,
  RECLAIM_USER_MESSAGE
} from '../../store/reducer/message'
import socket from '../../socket/Chatsocket'
import { themes } from '../../theme'
import { SET_CURRENT_USER } from '../../store/actions'

export default function index() {
  
  const route = useRoute()
  const dispatch = useDispatch();
  const {params} = route
  const navigation = useNavigation()
  const [loaded, setLoaded] = useState(false);
  const [message, setMessage] = useState([])
  const makeSocketUrl = () => {
   return  user.userId>params.fid? user.userId+'_'+params.fid + '/': params.fid+"_"+user.userId + '/'
  }
  const friendMap = useSelector(state => state.user.friendMap);
  const user = useSelector(state=> state.user.currentUser)
  const messageMap = useSelector(state => state.message.messageMap);
  const messagesList = useSelector(state => state.message.messages);
  const friendInfo = friendMap[params.fid]
  // alert(JSON.stringify(friendInfo))

  // const friendInfo = friendMap[params.fid];
  // 通过好友id获取好友消息数组中的hash，在用hash值到messageMap里面映射对应应的消息数据
  // {"1": ["188c3c16-0913-4688-ba9e-3867045efc6a", "fa06b8a2-3da1-423c-a4b1-bab5dfc7f103"]}
  // {"188c3c16-0913-4688-ba9e-3867045efc6a": {"content": "xxcv", "content_type": "text", "create_time": 2021-04-30T13:00:48.774Z, "dist_type": "private", "fid": 1, "hash": "188c3c16-0913-4688-ba9e-3867045efc6a", "isGroup": false, "is_owner": 1, "is_received": 1, "userId": 2}}
  const list = messagesList[params.fid+''] || [];
 
  const dealRawChatData = ()=> {
    const cookedList = []
    list.forEach(item=> {
      const itemData = messageMap[item]
      const uid = itemData.uid
      cookedList.unshift({
        _id: itemData.hash,
        [itemData.content_type]: itemData.content,
        createdAt: itemData.create_time,
        user: {
          _id: uid,
          name: uid===user.userId? user.username: friendMap[uid].fname,
          avatar: uid===user.userId? user.avatar: friendMap[uid].avatar,
        },
      })
    })
    setMessage(cookedList)
  }

  useEffect(() => {
    socket.setUp(makeSocketUrl())
    dispatch({type: UPDATE_CURRENT_CHAT_USER, payload:{ currentChatUserId: params.fid } })
    dispatch({type: RESET_CHAT_UNREAD_NUMBER, payload: {fid: params.fid, currentUserId: user.userId}})
    return () => {
      dispatch({ type: UPDATE_CURRENT_CHAT_USER, payload: { currentChatUserId: 0 } });
      dispatch({ type: RECLAIM_USER_MESSAGE, payload: { fid:params.fid } });
      socket.close_soket()
    }
  }, [])

  useEffect(() => {
    dealRawChatData()
  }, [list.length])


  const onSend = useCallback((messages = []) => {
    socket.sendMessage(messages, params?.fid)
  }, [])

  const test = () => {
    alert('test')
  }
  
  return (
    <SafeAreaView style={{...styles.container, backgroundColor: themes['light'].bg}}>
      <Header title={friendInfo?.fname} right={<Text>...</Text>} />
      {/* <Text>dadjasdjasodajsdoas</Text> */}
      <GiftedChat
        messages={message}
        onSend={messages => onSend(messages)}
        showUserAvatar
        showAvatarForEveryMessage
        renderAvatarOnTop
        focusTextInput={test}
        // isLoadingEarlier
        onLoadEarlier={test}
        
        loadEarlier
        infiniteScroll
        user={{
          _id: user.userId,
          name: user.username,
          avatar: 'https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png',
        }}
      />
    </SafeAreaView>
  )
}

const styles = StyleSheet.create({
  container: {
    paddingLeft: pxToPt(20),
    paddingRight: pxToPt(20),
    flex: 1,
  },
  chatBody: {
    flex: 1,
  },
  messageItem: {
    height: pxToPt(80),
    
  },
  avatar: {
    height: pxToPt(40),
    width: pxToPt(40),
    borderRadius: pxToPt(50)
  },
  messageWrapper: {
    marginLeft: pxToPt(10),
    marginRight: pxToPt(10),
    alignSelf: 'center',
    maxWidth: pxToPt(260),
    borderRadius: pxToPt(20),
    backgroundColor: 'rgb(34,36,46)',
    padding: pxToPt(10),

  },
  messageTxt: {
    color: 'rgb(155, 156, 178)',
  },
  inputBar: {
    flexDirection: 'row',
    justifyContent: 'space-around',
    backgroundColor: 'transparent'
  },
  input: {
    flex: 1,
    height: pxToPt(40),
    borderWidth: pxToPt(1),
    borderColor: '#fff',
    backgroundColor: 'rgb(238,240,241)',
    borderRadius: pxToPt(5),
    // marginRight: pxToPt(10),

  },
  button:{
    backgroundColor: 'rgb(34,36,46)',
    // borderRadius: pxToPt(20),
    width: pxToPt(50),
    height:pxToPt(40),
    justifyContent: 'center',
    alignItems: 'center'
  }
})
